﻿using BingSpatialDataServiceExcelAddin.BSDSTools;
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace BingSpatialDataServiceExcelAddin.Views
{
    /// <summary>
    /// Interaction logic for DownloadPanel.xaml
    /// </summary>
    public partial class DownloadPanel : UserControl
    {
        public DownloadPanel(System.Windows.Forms.Form parent)
        {
            InitializeComponent();

            ParentForm = parent;
        }

        public System.Windows.Forms.Form ParentForm { get; set; }

        public void Download(string queryURL, string masterKey, bool isPublic, string fileName)
        {
            int minIdx = "https://spatial.virtualearth.net/REST/v1/data/".Length;
            string accessId = null, dataSourceName = null;

            if (minIdx > -1 && queryURL.Length > minIdx)
            {
                int maxIdx = queryURL.IndexOf('/', minIdx);
                accessId = queryURL.Substring(minIdx, maxIdx - minIdx);

                minIdx = maxIdx + 1;
                maxIdx = queryURL.IndexOf('/', minIdx);
                dataSourceName = queryURL.Substring(minIdx, maxIdx - minIdx);
            }

            DataSourceService service = new DataSourceService();

            service.DownloadCompleted += (r) =>
            {    
                ElapsedTimer.IsStarted = false;

                DisplayMessage("Download Log", r + string.Format("\r\nDownload Completed in {0}.\r\n", ElapsedTimer.Text));

                ParentForm.Close();
            };

            service.ProgressChanged += (x) =>
            {
                Status.Text = x;
            };

            if (!string.IsNullOrWhiteSpace(accessId) && !string.IsNullOrWhiteSpace(dataSourceName))
            {
                ElapsedTimer.IsStarted = true;
                service.Download(fileName, accessId, dataSourceName, masterKey, isPublic);                
            }
            else
            {
                MessageBox.Show("Error: Unable to extract Data Source Access ID and Name from Query URL.");
                ParentForm.Close();
            }
        }

        private void DisplayMessage(string title, string msg)
        {
            OutputModal form = new OutputModal(title, msg);
            System.Windows.Forms.NativeWindow xlMain = new System.Windows.Forms.NativeWindow();
            xlMain.AssignHandle(new IntPtr(Globals.ThisAddIn.Application.Hwnd));

            form.ShowDialog(xlMain);
            form.Dispose();
            xlMain.ReleaseHandle();
        }
    }
}
